package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 鉴权过滤器
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private IgnoreWhiteConfig ignoreWhiteConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> whites = ignoreWhiteConfig.getWhites();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (StringUtils.matches(path, whites)) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        if (StringUtils.isBlank(token)) {
            return GatewayUtils.errorResponse(exchange, "无权访问");
        }
        try {
            JwtUtils.parseToken(token);
        } catch (Exception ex) {
            return GatewayUtils.errorResponse(exchange, "token不合法");
        }
        String userKey = JwtUtils.getUserKey(token);
        if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey)) {
            return GatewayUtils.errorResponse(exchange, "token过期");
        } else {
            Long remainingExpireTime = redisTemplate.getExpire(TokenConstants.LOGIN_TOKEN_KEY + userKey, TimeUnit.SECONDS);
            if (remainingExpireTime <= 600) {
                redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY + userKey, 900, TimeUnit.SECONDS); // 900 秒即 15 分钟
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}














































